"""
qtile的设置文件，适用于max模式下的窗口。精简大多数无用设置。
"""
from fontawesome import icons
from typing import List  # noqa: F401
from libqtile import bar, layout, widget, hook, qtile
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
import os
import subprocess


mod = "mod4"
terminal = guess_terminal()

BLACK = '#29414f'
RED = '#ec5f67'
GREEN = '#99c794'
YELLOW = '#fac863'
BLUE = '#6699cc'
MAGENTA = '#c594c5'
CYAN = '#5fb3b3'
WHITE = '#ffffff'

keys = [
    # 布局模式切换
    Key([mod], "Tab", lazy.next_layout(), desc="Toggle between layouts"),

    # 切换max模式下，同一个layout下的窗口。
    Key([mod], "Up", lazy.layout.up(), desc="Move focus up"),
    Key([mod], "Down", lazy.layout.down(), desc="Move focus down"),
    
    # 设置终端启动
    Key([mod], "Return", lazy.spawn(terminal), desc="Launch terminal"),

    # 关闭focused窗口
    Key([mod], "w", lazy.window.kill(), desc="Kill focused window"),

    Key([mod, "control"], "r", lazy.restart(), desc="Restart Qtile"),
    Key([mod, "control"], "q", lazy.shutdown(), desc="Shutdown Qtile"),
    Key([mod], "r", lazy.spawncmd(),
        desc="Spawn a command using a prompt widget"),
]

groups = [Group(i) for i in "123456789"]

layouts = [
    layout.Columns(border_focus_stack='#d75f5f'),
    layout.Max(),
]

widget_defaults = dict(
    font='monosapce',
    fontsize=12,
    padding=1,
)
extension_defaults = widget_defaults.copy()

screens = [
    Screen(
        wallpaper='/usr/share/wallpapers/jpg/23.jpg',
        wallpaper_mode='fill',
        top=bar.Bar(
            [
                widget.CurrentLayout(),
                widget.GroupBox(),
                widget.TaskList(),
                widget.Prompt(),
                widget.Chord(
                    chords_colors={'launch': ("#ff0000", "#ffffff"),},
                    name_transform=lambda name: name.upper(),),
                widget.Systray(background=CYAN),
                widget.Volume(fmt=icons['volume-up']+'{}',padding=5,background=BLUE,volume_app='pavucontrol'),
                widget.Clock(format=icons['calendar-alt']+' %Y-%m-%d', background=GREEN,padding=5),
                widget.Clock(format=icons['clock']+' %H:%M:%S', background=BLUE,padding=5),
                widget.QuickExit(default_text =icons['sign-out-alt'], countdown_format="{}s",background=GREEN,padding=10),
            ],
            24,
            opacity=1,
        ),
    ),
]

# Drag floating layouts.
mouse = [
    # 按住mod，使用鼠标左键移动窗口位置
    Drag([mod], "Button1", lazy.window.set_position_floating(),
         start=lazy.window.get_position()),
    # 按住mod，使用鼠标右键改变窗口大小
    Drag([mod], "Button3", lazy.window.set_size_floating(),
         start=lazy.window.get_size()),
]

dgroups_key_binder = None
dgroups_app_rules = []  # type: List
main = None  # WARNING: this is deprecated and will be removed soon
follow_mouse_focus = True
bring_front_click = False
cursor_warp = False

### 浮动窗口设置。请输入`xprop`命令查询窗口的 wm_class 属性 
floating_layout = layout.Floating(float_rules=[
    *layout.Floating.default_float_rules,
    Match(wm_class='rofi'),
    Match(wm_class='baidunetdisk'),
    Match(wm_class="Places"),
    Match(wm_class='Galculator'),
    Match(wm_class='Pavucontrol'),
    Match(wm_class='nm-connection-editor'),
    Match(wm_class='qq'),
    Match(wm_class='thunderbird'),
    Match(wm_class='rhythmbox'),
])

auto_fullscreen = True
focus_on_window_activation = "smart"

wmname = "LG3D"


"""
cycle_workspaces
工作区间切换以及移动活动窗口的工作空间
"""
def cycle_workspaces(direction, move_window):
    def _inner(qtile):
        current = qtile.groups.index(qtile.current_group)
        destination = (current + direction) % len(groups)
        if move_window:
            qtile.current_window.togroup(qtile.groups[destination].name)
        qtile.groups[destination].cmd_toscreen()
    return _inner


next_workspace = lazy.function(cycle_workspaces(direction=1, move_window=False))
previous_workspace = lazy.function(cycle_workspaces(direction=-1, move_window=False))
to_next_workspace = lazy.function(cycle_workspaces(direction=1, move_window=True))
to_previous_workspace = lazy.function(cycle_workspaces(direction=-1, move_window=True))

keys.extend([
    Key(["control", "mod1"], "Right", next_workspace),
    Key(["control", "mod1"], "Left", previous_workspace),
    Key(["control", "mod1", "shift"], "Right", to_next_workspace),
    Key(["control", "mod1", "shift"], "Left", to_previous_workspace),
])


"""
弹出程序起动器rofi
"""
dmenu = "rofi -combi-modi window,drun,ssh -theme solarized -font 'Ubuntu Mono 15' -show combi -icon-theme 'Papirus' -show-icons"
keys.extend([
    Key([mod],"d", lazy.spawn(dmenu)),
])

"""
随着桌面环境启动的程序
"""
@hook.subscribe.startup_once
def autostart():
    home = os.path.expanduser('~/.config/qtile/autostart.sh')
    subprocess.call([home])
